<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属医院" prop="hospitalId">
        <el-select v-model="queryParams.hospitalId" placeholder="请选择医院" clearable filterable @change="queryHospitalChange">
          <el-option v-for="data in hospitalOptions" :key="data.value" :label="data.label" :value="data.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属科室" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择科室" clearable filterable @change="handleQuery">
          <el-option v-for="data in deptOptions" :key="data.value" :label="data.label" :value="data.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="fullName">
        <el-input v-model="queryParams.fullName" placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户账号" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户账号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['hospital:user:add']" >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['hospital:user:edit']" >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['hospital:user:remove']" >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="医院" align="center" prop="hospital" />
      <el-table-column label="科室" align="center" prop="dept" />
      <el-table-column label="姓名" align="center" prop="fullName" />
      <el-table-column label="用户角色" align="center" prop="userType" >
        <template slot-scope="scope">
          <span v-if="scope.row.userType === '00'" >医院</span>
          <span v-if="scope.row.userType === '01'" >医生</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phonenumber" />
      <el-table-column label="用户账号" align="center" prop="userName" />
      <el-table-column label="账号状态" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'" size="mini" type="success">正常</el-tag>
          <el-tag v-if="scope.row.status === '1'" size="mini" type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['hospital:user:edit']" >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['hospital:user:remove']" >删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-key" @click="handleReset(scope.row)" v-hasPermi="['hospital:user:edit']" >重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改医院用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户角色" prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio label="00">医院账号</el-radio>
            <el-radio label="01">医生账号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select v-model="form.hospitalId" placeholder="请选择医院" filterable @change="getDeptData" style="width: 100%;">
            <el-option v-for="data in hospitalOptions" :key="data.value" :label="data.label" :value="data.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.userType === '01'" label="所属科室" filterable prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择科室" style="width: 100%;">
            <el-option v-for="data in deptOptions" :key="data.value" :label="data.label" :value="data.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="form.fullName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户账号" prop="userName">
          <el-input v-model="form.userName" minlength="2" maxlength="20" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item v-if="isAdd" label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" minlength="5" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入用户邮箱" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listUser, getUser, delUser, addUser, updateUser, resetPassword} from "@/api/business/user";
import {getOptionData} from "@/api/business/hospital";
import {getDeptOptionData} from "@/api/business/dept";

export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医院用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isAdd: true,
      // 医院数据
      hospitalOptions: [],
      // 科室数据
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalId: null,
        deptId: null,
        fullName: null,
        userName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        hospitalId: [
          { required: true, message: "所属医院不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属科室不能为空", trigger: "blur" }
        ],
        fullName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "用户账号不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
    };
  },
  created() {
    this.getHospitalData();
    this.getList();
  },
  methods: {
    getHospitalData (){
      getOptionData().then(response => {
        this.hospitalOptions = response.data;
      });
    },
    getDeptData (val){
      this.queryParams.deptId = '';
      if(! val) {
        this.deptOptions = [];
      } else {
        getDeptOptionData(val).then(response => {
          this.deptOptions = response.data;
        });
      }
    },
    queryHospitalChange(val){
      this.getDeptData(val);
      this.handleQuery();
    },
    /** 查询医院用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        hospitalId: null,
        deptId: null,
        fullName: null,
        userType: '00',
        email: null,
        phonenumber: null,
        userName: null,
        password: '123456',
        status: '0',
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isAdd = true;
      this.title = "添加医院用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      getUser(userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.isAdd = false;
        this.title = "修改医院用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('该操作不可撤销，是否确认删除所选用户？').then(function() {
        return delUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 重置密码操作 */
    handleReset(row) {
      this.$prompt('请输入"' + row.fullName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({ value }) => {
        resetPassword(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {});
    },
  }
};
</script>
